#include "Situation.h"
#include "ui_Situation.h"
#include "Mainpage.h"
#include <QTcpSocket>
#include <QMessageBox>
#include <QLayout>
#include <QBitmap>
#include <QStyleOption>
#include <QtCharts/QLegendMarker>
#include "mymessagebox.h"

Situation::Situation(const QString &id, QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Situation)
    , employeeId(id)  // 通过构造函数传递工号
    , tcpSocket(new QTcpSocket(this))
{
    ui->setupUi(this);

    // 隐藏原生标题栏
    setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog);

    // 防止窗口背景透明
    setAttribute(Qt::WA_TranslucentBackground, false);

    // 连接服务器并发送工号
    tcpSocket->connectToHost("127.0.0.1", 12354);
    connect(tcpSocket, &QTcpSocket::readyRead, this, &Situation::onDataReceived);

    // 发送请求
    QString request = QString("GET_ATTENDANCE_SUMMARY|%1").arg(employeeId);
    tcpSocket->write(request.toUtf8());
}

Situation::~Situation()
{
    delete ui;
}

// 实现窗口拖动功能
void Situation::mousePressEvent(QMouseEvent *event)
{
    // 检查是否点击了自定义标题栏
    if (event->button() == Qt::LeftButton && event->pos().y() <= 50) {
        m_isTitleBarClicked = true;
        m_dragPosition = event->globalPos() - frameGeometry().topLeft();
        event->accept();
    } else {
        m_isTitleBarClicked = false;
        // 让事件继续传播，确保其他控件能响应点击事件
        QWidget::mousePressEvent(event);
    }
}

void Situation::mouseMoveEvent(QMouseEvent *event)
{
    // 只有在点击了标题栏之后才允许拖动
    if (m_isTitleBarClicked && (event->buttons() & Qt::LeftButton)) {
        move(event->globalPos() - m_dragPosition);
        event->accept();
    } else {
        // 让事件继续传播，确保其他控件能响应移动事件
        QWidget::mouseMoveEvent(event);
    }
}

void Situation::paintEvent(QPaintEvent *event)
{
    // 1. 绘制样式（QSS）
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); // 绘制样式

    // 2. 设置掩码，约定 painter 绘制区域
    QBitmap bmp(this->size());
    bmp.fill(Qt::white); // 填充 bitmap

    QPainter painter(&bmp);
    painter.setPen(Qt::NoPen);
    painter.setBrush(Qt::black); // 掩码值
    painter.drawRoundedRect(bmp.rect(), 20, 20); // 在 bitmap 中绘制圆角矩形

    // 手动绘制边框
    QPainter borderPainter(this);
    borderPainter.setRenderHint(QPainter::Antialiasing);
    QPen pen(QColor("#55aaff")); // 设置边框颜色
    pen.setWidth(2);              // 设置边框宽度
    borderPainter.setPen(pen);
    borderPainter.setBrush(Qt::NoBrush);
    QRect rect = this->rect();
    rect.adjust(1, 1, -1, -1); // 调整边框矩形，以确保边框在控件内部
    borderPainter.drawRoundedRect(rect, 20, 20); // 绘制圆角边框

    // 设置掩码以确定本控件可绘制区域
    setMask(bmp);

    // 调用基类的 paintEvent
    QWidget::paintEvent(event);
}

void Situation::on_returnButton_clicked()
{
    this->close();
}

// 接收服务器数据
void Situation::onDataReceived()
{
    QByteArray responseData = tcpSocket->readAll();
    QString response = QString::fromUtf8(responseData);

    if (response.startsWith("SUMMARY|")) {
        QStringList data = response.split("|");
        int totalCheckIns = data[1].toInt();
        int successfulCheckIns = data[2].toInt();
        int resignCounts = data[3].toInt();
        int leaveCounts = data[4].toInt();
        int missingCheckIns = data[5].toInt();

        drawPieChart(totalCheckIns, successfulCheckIns, resignCounts, leaveCounts, missingCheckIns);
    } else {
        // QMessageBox::warning(this, "错误", "未能获取考勤信息");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("未能获取考勤信息");
        msgBox.setButton("确定");
        msgBox.exec();
    }
}

// 绘制饼状图
void Situation::drawPieChart(int totalCheckIns, int successfulCheckIns, int resignCounts, int leaveCounts, int missingCheckIns)
{
    using namespace QtCharts;

    QPieSeries *series = new QPieSeries();

    // 设置字体样式
    QFont labelFont;
    labelFont.setFamily("华文琥珀");
    labelFont.setPointSize(10);

    // 添加各部分，并设置标签显示数据
    QPieSlice *successfulSlice = series->append("已打卡", successfulCheckIns);
    successfulSlice->setLabel(QString("已打卡: %1").arg(successfulCheckIns));
    successfulSlice->setLabelFont(labelFont);

    QPieSlice *resignSlice = series->append("补签次数", resignCounts);
    resignSlice->setLabel(QString("补签次数: %1").arg(resignCounts));
    resignSlice->setLabelFont(labelFont);

    QPieSlice *leaveSlice = series->append("请假次数", leaveCounts);
    leaveSlice->setLabel(QString("请假次数: %1").arg(leaveCounts));
    leaveSlice->setLabelFont(labelFont);

    QPieSlice *missingSlice = series->append("未打卡", missingCheckIns);
    missingSlice->setLabel(QString("未打卡: %1").arg(missingCheckIns));
    missingSlice->setLabelFont(labelFont);

    // 设置标签可见
    series->setLabelsVisible(true);

    // 创建图表并设置系列
    QChart *chart = new QChart();
    chart->addSeries(series);
    chart->setTitle("考勤情况");

    // 设置图表样式
    chart->setBackgroundBrush(QBrush(QColor("#aaffff"))); // 设置背景颜色
    chart->setBackgroundPen(QPen(QColor("#55aaff"), 5));  // 设置边框颜色和宽度
    chart->setTitleFont(labelFont);

    // 设置图例样式
    QLegend *legend = chart->legend();
    legend->setVisible(true);
    legend->setAlignment(Qt::AlignBottom); // 设置图例的位置

    // 设置图例文本样式
    QFont legendFont;
    legendFont.setFamily("华文琥珀");
    legendFont.setPointSize(6);
    legendFont.setWeight(QFont::Medium);
    legend->setFont(legendFont); // 设置图例字体

    // 设置图例文本颜色
    legend->setLabelColor(QColor("#00aaff"));

    // 设置每个图例项的自定义样式
    for (QLegendMarker *marker : chart->legend()->markers()) {
        marker->setLabelBrush(QBrush(QColor("#00aaff"))); // 设置图例文本颜色
        marker->setFont(legendFont); // 设置图例字体
    }

    // 创建ChartView并启用抗锯齿
    QChartView *chartView = new QChartView(chart);
    chartView->setRenderHint(QPainter::Antialiasing);

    // 检查并添加布局
    if (!ui->widget->layout()) {
        QVBoxLayout *layout = new QVBoxLayout(ui->widget);
        ui->widget->setLayout(layout);
    }
    ui->widget->layout()->addWidget(chartView);

    // 设置背景颜色为 #00ffff
    ui->widget->setStyleSheet("background-color: #00ffff;");

}
